package pl.oczadly.jabberclient.login.model;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;

import pl.oczadly.jabberclient.connection.ConnectionHolder;

public class LoginModel implements ILoginModel {

	public boolean signIn( String login, String password ) {
		// initialize connection:
		ConnectionHolder.getInstance();
		
		ConnectionConfiguration config = ConnectionHolder.getConfig();
		config.setSASLAuthenticationEnabled( true );
		XMPPConnection connection = ConnectionHolder.getConnection();

		config.setSASLAuthenticationEnabled( false );
		config.setSecurityMode( SecurityMode.disabled );

		
		SASLAuthentication.supportSASLMechanism( "PLAIN", 0 );
		System.out.println( "Connecting to " );
		try {
			connection.connect();
	
			System.out.print( " logging in with username: " + login + ";" );
			connection.login( login, password, "zasob" );
			if( connection.isAuthenticated() ) {
				System.out.print( " authenticated;" );
				Presence presence = new Presence( Presence.Type.available );
				
				connection.sendPacket( presence );
				return true;
			} else {
				System.out.print( " login failed!" );
				return false;
			}
		} catch( XMPPException e ) {
			return false;
		}
		
	}
	
}
